package com.frame.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.frame.Page;
import com.frame.domain.User;
import com.frame.support.Tree;
import com.mini.core.PageResult;
import com.mini.core.Record;
import com.mini.core.dao.MiniDao;
import com.mini.core.utils.StrKit;

/**
 * DAO for {@link User}.
 */
@Service
public class UserService{

	@Autowired
	MiniDao miniDao;
	
	/**
	 * 查找所有用户
	 * @return
	 */
	public List<User> findAll(){
		String sql = "SELECT * FROM USERS";
		return miniDao.findList(sql, User.class);
	}
	
	/**
	 * 分页查询用户
	 * @param page
	 * @param treeId
	 * @return
	 */
	public Page<Record> paginateResult(Page<Record> page,String treeId){
		String sql = "SELECT u.*,d.NAME as DEPTNAME FROM USERS u,DEPARTMENT d WHERE 1=1 AND u.DEPTID=d.ID";
		PageResult<Record> users = null;
		if(StrKit.notBlank(treeId) && !Tree.TREE_ROOT_ID.equals(treeId)){
			sql+=" AND (u.DEPTID=? OR u.ID =?)";
			users = miniDao.paginateResult(sql, page.getPageNo(), page.getPageSize(), Record.class,treeId,treeId);
		}else
			users = miniDao.paginateResult(sql, page.getPageNo(), page.getPageSize(), Record.class);
		page.setPageResult(users);
		return page;
	}

	/**
	 * 插入数据
	 * @param user
	 */
	public void save(User user) {
		miniDao.insert(user);
	}
	
	/**
	 * 更新数据
	 * @param user
	 */
	public void update(User user) {
		miniDao.update(user);
	}
	
	/**
	 * 根据Id删除用户
	 * @param id
	 */
	public void delete(String id){
		miniDao.deleteById(User.class, id);
	}

	/**
	 * 获取用户
	 * @param id
	 * @return
	 */
	public User findById(String id) {
		return miniDao.findById(User.class, id);
	}
	
	
	///////////////////////////////////////////////////////////
	
	public User findByEmail(String email){
		String sql = "SELECT * FROM USERS WHERE EMAIL=?";
		return miniDao.find(sql, User.class, email);
	}
	
	/**
	 * 分页查询用户
	 * @param page
	 * @param treeId
	 * @return
	 */
	public Page<Record> paginateResult(Page<Record> page){
		String sql = "SELECT u.*,d.name as deptname FROM USERS u,DEPARTMENT d WHERE 1=1 AND u.DEPTID=d.ID";
		PageResult<Record> users = miniDao.paginateResult(sql, page.getPageNo(), page.getPageSize(), Record.class);
		page.setPageResult(users);
		return page;
	}

	public User findByEmailAndActive(String email, boolean active){
		try {
			String sql = "SELECT * FROM USERS WHERE EMAIL=? AND ACTIVE=?";
			return miniDao.find(sql, User.class, email, active);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public void deleteAll() {
		
	}

}
